// 目标是多个代理接口api  例如 /api ===> target http:127.0.0.1/api
/*
{
  target: apiUrl,
  changeOrigin: true,
  secure: false,
  pathRewrite: {
    '^/apiKey': ''
  }
}
针对不同环境
test: {
  apiKey: apiUrl,
  apiKey1: apiUrl1,
  apiKey2: apiUrl2
},
dev: {
  apiKey: apiUrl,
  apiKey1: apiUrl1,
  apiKey2: apiUrl2
},
prod: {
  apiKey: apiUrl,
  apiKey1: apiUrl1,
  apiKey2: apiUrl2
}
*/

// 最终目标使用 koa 调用 nuxt 来渲染页面
import Koa from 'koa'
import { Nuxt, Builder } from 'nuxt' // 加载 nuxt
import config from '../nuxt.config.js' // 加载 nuxt 配置
import Proxy from './proxy.js' // 记载 proxy
import api from './api.js' // 加载 api 配置

// 创建应用
const app = new Koa()

async function start() {
  // 创建代理程序
  const proxy = new Proxy(app)

  // 需要通过 koa 中间件来代理
  Object.keys(api[process.env.NUXT_ENV_MODE]).forEach((apiKey) => {
    console.log(
      'apiKey====>',
      apiKey,
      'apiUrl====>',
      api[process.env.NUXT_ENV_MODE][apiKey]
    )
    proxy.intall(apiKey, api[process.env.NUXT_ENV_MODE][apiKey])
  })

  const nuxt = new Nuxt(config) // 实例化配置

  config.dev = !(app.env === 'production')
  // 拿到 host,port
  const {
    host = process.env.HOST || '127.0.0.1',
    port = process.env.PORT || 9000,
  } = nuxt.options.server

  // 启动页面服务
  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  // 调用 nuxt 中间件来渲染页面
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  app.listen(port, host)

  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true,
  })
}

start()